<template>
	<div id="container">
		<div id="myheader">
			<span>我的购物车</span>
		</div>
		<div id="cart_content">
			<el-table :data="tableData" border style="width: 100%" height="500px"
				@selection-change="cartSelectionChange">

				<el-table-column align="center" label="全选" type="selection" width="55">
				</el-table-column>
				<el-table-column fixed prop="imageUrl" label="商品图片" min-width="3%">
					<template slot-scope="scope" v-if="scope.row.imageUrl">
						<!-- <el-button size="mini" @click="findimage(scope.row)">查看</el-button> -->
						<el-image style="width: 100px; height: 50px"
							:src="require('@/assets/equipments/'+scope.row.imageUrl)"
							:preview-src-list="[require('@/assets/equipments/'+scope.row.imageUrl)]" />
					</template>
				</el-table-column>
				<el-table-column fixed prop="name" label="商品信息" min-width="6%">
					<template slot-scope="scope">
						<div class="blue-font-color" @click="toDetails(scope.row.name)">{{ scope.row.name}}</div>
					</template>
				</el-table-column>
				<el-table-column prop="realPrice" label="现价" :formatter="rounding" min-width="4%">
				</el-table-column>
				<el-table-column prop="price" label="原价" :formatter="rounding" min-width="4%">
				</el-table-column>
				<el-table-column label="数量" align="center" prop="count,id" min-width="7%">
					<!-- 使用计数器来添加数量，绑定表格数据行对应的count -->
					<template slot-scope="scope">
						<el-input-number size="medium" v-model="scope.row.count"
							@change="handleChange(scope.row.id,scope.row.count)" :min="1" :max="10"></el-input-number>
					</template>
				</el-table-column>
				<el-table-column label="小计" prop="subtotal" align="center" min-width="4%">
					<template slot-scope="money">
						<span>￥{{(money.row.price*money.row.count).toFixed(2)}}</span>
					</template>
				</el-table-column>
				<el-table-column fixed="right" label="操作" min-width="6%">
					<template slot-scope="scope">
						<el-button @click.native.prevent="deleteRow(scope.row.id)" type="danger" icon="el-icon-delete"
							size="small">
						</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>


		<div id="cart_button">
			<el-button type="warning" style="margin-top: 10px;margin-left: 30px;"
				@click="batchDeleteCartGoods"><span>删除选中的商品</span></el-button>
			<div class="cart_num">已选择<span class="total-num">{{this.selectGoodsList.length}}</span>种商品</div>
			<div class="cart_total_price">总价：<span class="total-price">￥{{cartTotalPrice}}</span></div>

			<el-button type="danger" style="margin-top: 10px;margin-right: 30px;" @click="toMyOrder()">结算</el-button>

		</div>
	</div>
</template>

<script>
	import request from '@/utils/axios/request.js';
	export default {
		inject: ['reload'],
		data() {
			return {

				sum: 0,
				uCId: '',
				// equipmentsList: [{
				// 	imageUrl: '',
				// 	name: '',
				// }],
				selectGoodsList: [],
				tableData: [{
					// goodsName: 'asdf ',
					id: '',
					imageUrl: '',
					name: '',
					realPrice: '',
					price: '',
					count: '',
					goodsPrice: ''
				}, ]
			}
		},
		methods: {
			//生成购买订单
			toMyOrder() {
				// console.log(this.selectGoodsList)
				// console.log('this.selectGoodsList')
				var id = [];
				console.log(this.selectGoodsList)
				this.selectGoodsList.forEach((item) => {
					id.push(item.id);
				})
				// console.log('id');
				// console.log(id);
				request({
					method: 'delete',
					url: '/userCartDetails/deleteUserCartDetails',
					data: id
				
				}).then((res) => {
					// console.log(res)
					// this.reload();
				})
				this.$router.push({
					path: 'myOrder',
					query: {
						data: this.selectGoodsList
					}
				})
			},
			// 单个删除购物车商品
			deleteRow(id) {
				this.$confirm('此操作将移除购物车的商品, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(async () => {
					request({
						method: 'delete',
						url: '/userCartDetails/' + id,
					}).then((res) => {
						// console.log(res)
						this.reload();
					})
				}).catch((e) => {
					// console.log(e)
					this.$message.info('已取消删除')
				})
			},
			// 批量删除购物车商品
			batchDeleteCartGoods() {
				var item = this.selectGoodsList
				if (this.selectGoodsList.length > 0) {} else {
					return this.$message.error('请勾选要移除购物车的商品')
				}
				this.$confirm('此操作将移除勾选的购物车的商品, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(async () => {
					// 这里调用接口删除的方法
					var id = [];
					console.log(this.selectGoodsList)
					this.selectGoodsList.forEach((item) => {
						id.push(item.id);
					})
					// console.log('id');
					// console.log(id);
					request({
						method: 'delete',
						url: '/userCartDetails/deleteUserCartDetails',
						data: id

					}).then((res) => {
						// console.log(res)
						this.reload();
					})
				}).catch((e) => {
					// console.log(e)
					var id = [];
					this.selectGoodsList.forEach((item) => {
						id.push(item.id);
					})
					console.log(id);
					this.$message.info('已取消删除')
				})
			},
			toDetails(name) {
				// console.log(name)
				this.$router.push({
					path: '/equipmentDetails',
					query: {
						clickSearch: name
					}
				})

			},
			// 购物车选择事件（elemenUI表格勾选保存的值）
			cartSelectionChange(val) {
				// console.log(val)
				this.selectGoodsList = val

			},
			//保留两位小数
			rounding(row, column) {
				return parseFloat(row[column.property]).toFixed(2)
			},

			handleChange(id, count) {
				// console.log(id)
				// console.log(count);	
				request({
					method: 'post',
					url: '/userCartDetails/count',
					params: {
						num: count,
						uCDId: id
					}
				}).then((res) => {
					// console.log(res)
				})
			},

			// getSum(param) {
			// 	const {
			// 		columns,
			// 		data
			// 	} = param;
			// 	const sums = [];
			// 	// console.log(columns, data);
			// 	columns.forEach((column, index) => {
			// 		if (index === 0) {
			// 			sums[index] = "合计";
			// 			return;
			// 		}
			// 		//calcProp 为需要计算的列的prop值的集合
			// 		const calcProp = ["count", "subtotal"];
			// 		if (calcProp.includes(column.property)) {
			// 			const values = data.map(item => Number(item[column.property]));
			// 			sums[index] = values.reduce((prev, curr) => {
			// 				const value = Number(curr);
			// 				if (!isNaN(value)) {
			// 					return prev + curr;
			// 				} else {
			// 					return prev;
			// 				}
			// 			}, 0);
			// 		}
			// 	});
			// 	return sums;
			// },
		},
		computed: {
			cartTotalPrice() {
				let sum = 0
				this.selectGoodsList.forEach(item => {
					sum += item.realPrice * item.count
				})
				// 因为要保留小数点后面两位，所以要toFixed(2)
				return sum.toFixed(2)
			}

		},

		created() {
			var p = 0
			// 方法一，复杂嵌套容易形成回调地狱
			request({
				method: 'get',
				url: '/userCart/' + '123',
			}).then((res) => {
				// console.log(res.data.data)
				this.uCId = res.data.data
				// console.log(this.uCId)
				request({
					method: 'get',
					url: '/userCartDetails/' + this.uCId,
				}).then((res2) => {
					// console.log(res2)
					res2.data.data.forEach(item => {
						this.$set(item, 'name', '')
						this.$set(item, 'imageUrl', '')
					})
					// console.log(res2)
					// console.log("res2")
					var jsonObj = JSON.parse(JSON.stringify(res2.data.data));
					// console.log("jsonObj")
					// console.log(jsonObj)
					// console.log("jsonObj")
					for (var i = 0; i < jsonObj.length; i++) {
						// console.log(jsonObj[i].eId)
						request({
							method: 'get',
							url: '/equipments/' + jsonObj[i].eId,
						}).then((res3) => {
							// console.log("res3")
							// console.log(res3)
							// console.log("res3")
							var equipmentsObj = JSON.parse(JSON.stringify(res3.data.data));
							// console.log("jsonObj")	
							// console.log(p)
							jsonObj[p].name = equipmentsObj.eName
							jsonObj[p].imageUrl = equipmentsObj.imageUrl
							p++
							// console.log(p)
							// console.log("jsonObj")
							// console.log("equipmentsObj")
							// console.log(equipmentsObj)
							// console.log("equipmentsObj")				
						})
						// console.log(res2)
						// console.log('546456')
						jsonObj[i].id = jsonObj[i].userCartDetailsId;
						jsonObj[i].realPrice = jsonObj[i].eRealprice;
						jsonObj[i].price = jsonObj[i].ePrice;
						jsonObj[i].count = jsonObj[i].eCount;
					}
					this.tableData = jsonObj
					// console.log("this.tableData")
					// console.log(this.tableData)
					// console.log("this.tableData")
				})

			})

		}

	}
</script>

<style>
	.blue-font-color:hover {
		cursor: pointer;
	}

	.el-input-number--medium {
		width: 150px !important;
	}

	.el-table__header {
		height: 40px;
		line-height: 40px;
		background-color: #55aa7f;
	}

	.el-input-number {
		.el-input {
			margin: 0 auto;
		}
	}

	#cart_button {
		width: 100%;
		height: 46px;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		background-color: transparent;

	}

	.cart_num {
		height: 46px;
		margin-left: 38%;
		font-size: 24px;
		background-color: transparent;
		line-height: 46px;
	}

	.cart_total_price {
		height: 46px;
		color: red;
		font-size: 24px;
		background-color: transparent;
		line-height: 46px;
	}

	#cart_content {
		width: 100%;
		/* height: 100%-30px; */
		height: auto;
		background-color: #55ffff;
	}

	#myheader {
		width: 100%;
		height: 40px;
		/* margin-bottom: 200px; */
		line-height: 40px;
		font-size: 30px;
		background-color: #ffff7f;
	}

	#container {
		width: 100%;
		height: 700px;
		overflow-y: hidden;
		overflow-x: hidden;
		display: flex;
		flex-direction: column;
		justify-content: flex-start;
		align-items: center;
		background-color: #f4f4f4;
	}
</style>